#include"mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
myfile* buyfile(int fd,int flag)
{
  myfile* a=(myfile*)malloc(sizeof(myfile));
  a->fid=fd;
  a->flag=flag;
  a->bufferlen=0;
  a->flush_mthod=line;
  memset(a->outbuffer,0,sizeof(a->outbuffer));
  return a;
}
myfile* myfopen(const char* path,const char* mod)
{
  int fd=-1;
  int flag=0;
  if(strcmp(mod,"w")==0)
  {
    flag=O_CREAT | O_WRONLY | O_TRUNC;
    fd=open(path,flag,0666);
  }
  else if(strcmp(mod,"a")==0)
  {

    flag=O_CREAT | O_WRONLY | O_APPEND;
    fd=open(path,flag,0666);
  }
  else if(strcmp(mod,"r")==0)
  {

    flag=O_RDWR;
    fd=open(path,flag,0666);
  }
  if(fd<0)
  {
    return NULL;
  }
  return buyfile(fd,flag);
}
void myfclose(myfile* a)
{
  if(a->fid<0)
  {
    return;
  }
  myfflush(a);
  close(a->fid);
  free(a);
}
int myfwrite(myfile* file,void* str,int len)
{
  // 1. 拷贝
    memcpy(file->outbuffer+file->bufferlen, str, len);
    file->bufferlen += len;
    // 2. 尝试判断是否满足刷新条件！
    if((file->flush_mthod & line) && file->outbuffer[file->bufferlen-1] == '\n')
    {
        myfflush(file);
    }
    return 0;
}
void myfflush(myfile* file)
{
   if(file->bufferlen <= 0) return;
    // 把数据从用户拷贝到内核文件缓冲区中
    int n = write(file->fid, file->outbuffer, file->bufferlen);
    (void)n;
    fsync(file->fid);
    file->bufferlen = 0;
}
